package com.myappengine.controller;

import java.util.logging.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.myappengine.service.MovieService;

@Controller
@RequestMapping("/movie")
public class MovieController {
	
	private static Logger logger = Logger.getLogger(MovieController.class.getCanonicalName());
	
	@Autowired
	private MovieService movieService;
	
	@RequestMapping(value="/{name}", method = RequestMethod.GET)
	public String getMovie(@PathVariable String name, ModelMap model) {
		model.addAttribute("movie", movieService.getMovieName());
		return "list";
	}
	
	@RequestMapping(value = "/addEntity", method = RequestMethod.GET)
	public String addEntityTree(ModelMap model) throws Exception {
		DatastoreService service = DatastoreServiceFactory.getDatastoreService();
		Entity e1 = new Entity("Employee", "key employee1");
		e1.setProperty("Name", "Name Employee 1");
		service.put(e1);
		Entity e2 = new Entity("Employee", "key employee2", e1.getKey());
		e2.setProperty("Name", "Name Employee 2");
		service.put(e2);
		Entity e3 = new Entity("Employee", "key employee3", e2.getKey());
		e3.setProperty("Name", "Name Employee 3");
		service.put(e3);
		Entity e4 = new Entity("Employee", "key employee4", e3.getKey());
		e4.setProperty("Name", "Name Employee 4");
		service.put(e4);
		
		// Create key for retrieving e4
		Key k4 = new KeyFactory.Builder("Employee", "key employee1")
				.addChild("Employee", "key employee2")
				.addChild("Employee", "key employee3")
				.addChild("Employee", "key employee4")
				.getKey();
		String s = k4.toString();
		model.addAttribute("key", s);
		Entity e = service.get(k4);
		model.addAttribute("e4", e);
		return "list";
	}
}